<template>
  <div class="div_padding">
    <el-form
      :inline="true"
      :model="formInline"
      ref="formInline"
      class="demo-form-inline"
      size="small"
    >
      <el-form-item label="雇员名字：" prop="name">
        <el-input v-model="formInline.name" placeholder="雇员名字"></el-input>
      </el-form-item>
      <el-form-item label="雇员手机号/email：" prop="mobile">
        <el-input v-model="formInline.mobile" placeholder="支持手机号及email查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" v-permission="'Search'" type="primary" @click="filterData"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" plain @click="resetForm('formInline')"
          >重置</el-button
        >
        <el-button icon="el-icon-plus" v-permission="'Create'" type="success" @click="onSubmit"
          >添加员工</el-button
        >
        <Insert ref="insert" @reloadTable="reloadTable"></Insert>
        <Edit
          ref="edit"
          :deptData="this.deptOptions"
          :roleData="this.roleOptions"
          @reloadTable="reloadTable"
        ></Edit>
      </el-form-item>
      <el-button
        style="float: right"
        icon="el-icon-refresh-right"
        circle
        @click="reloadTable"
      ></el-button>
    </el-form>
    <el-table
      :data="tableData"
      size="small"
      height="72vh"
      v-loading="loading"
      empty-text="查询结果为空!"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      style="width: 100%; overflow-x: hidden"
      row-key="id"
      border
    >
      <el-table-column
        prop="id"
        label="ID"
        v-if="showId"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="avatar"
        label="avatar"
        v-if="showAvatar"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column label="序号" type="index" align="center" width="50">
      </el-table-column>
      <el-table-column prop="name" label="姓名" align="center" width="120">
      </el-table-column>
      <el-table-column prop="username" label="账号" align="center" width="120">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" align="center" width="150">
      </el-table-column>
      <el-table-column
        prop="dept"
        label="所属机构"
        align="center"
        width="180"
        :formatter="deptFormatter"
      >
      </el-table-column>
      <el-table-column
        prop="role"
        label="所属角色"
        align="center"
        width="150"
        :formatter="roleFormatter"
      >
      </el-table-column>
      <el-table-column prop="gender" label="性别" align="center" width="100">
        <template slot-scope="scope">
          <el-tag size="small" type="danger" v-if="scope.row.gender == 0">女</el-tag>
          <el-tag size="small" v-if="scope.row.gender == 1">男</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="is_active"
        width="100"
        align="center"
        label="账号状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.is_active == true" type="success" size="small"
            >正常</el-tag
          >
          <el-tag v-if="scope.row.is_active == false" type="danger" size="small"
            >停用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        label="备注"
        align="center"
        width="150"
      >
      </el-table-column>
      <el-table-column
        prop="update_datetime"
        label="更新时间"
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="create_datetime"
        label="创建时间"
        sortable
        align="center"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        prop="parent"
        fixed="right"
      >
        <template slot-scope="scope">
            <el-button
              type="primary"
              v-permission="'Update'"
              v-show="scope.row.username!='admin'"
              size="mini"
              @click="onEdit(scope.$index, scope.row)"
              icon="el-icon-edit"
              plain
              >修改</el-button
            >
            <el-button
              type="danger"
              v-show="scope.row.username!='admin'"
              v-permission="'Delete'"
              size="mini"
              icon="el-icon-delete"
              plain
              @click="onDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              v-permission="'DefaultPassword'"
              size="mini"
              icon="el-icon-setting"
              plain
              @click="onSetting(scope.row)"
              >重置密码</el-button
            >
        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="margin: 5px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="cur_page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { getUserData, delUserData,resetUserPassword } from "@/api/user";
import { getDeptData } from "@/api/dept";
import { getRoleData } from "@/api/role";
import { successMsg, errorMsg } from "@/utils/tools";
import Insert from "./insert";
import Edit from "./edit";
export default {
  name: "User",
  components: {
    Insert,
    Edit,
  },
  data() {
    return {
      showId: false,
      showAvatar: false,
      loading: true,
      tableData: [],
      total: 0,
      cur_page: 1,
      pageSize: 10,
      formInline: {
        name: "",
        mobile: "",
      },
      deptOptions: [],
      deptOptionsUnTree: [],
      roleOptions: [],
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      getUserData({page:this.cur_page,limit:this.pageSize}).then((res) => {
        this.tableData = res.data.data;
        this.total = res.data.total;
      });
      getDeptData({ status: "True" }).then((res) => {
        this.deptOptionsUnTree = res.data.data 
        this.deptOptions = this.$utils.toArrayTree(res.data.data,{ parentKey: 'parent', strict: true })
      });
      getRoleData({ status: "True" }).then((res) => {
        this.roleOptions = res.data.data;
      });
      this.loading = false;
    },
    onSubmit() {
      this.$refs.insert.dialogFormVisible = true;
    },
    onEdit(index, row) {
      this.$refs.edit.dialogFormVisible = true;
      this.$refs.edit.formInline = Object.assign({}, row); //formInline，将row的数据复制到editForm对象中，实现的是浅拷贝
    },
    onDelete(row) {
      this.$confirm("警告，谨慎操作!是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUserData(row.id).then((res) => {
            if (res.code === 2000) {
              successMsg(res.msg);
              this.reloadTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    reloadTable() {
      this.loading = true;
      this.fetchData();
    },
    filterData() {
      let params = {};
      if (this.formInline.name) {
        params.name = this.formInline.name;
      }
      var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
      if (!phonereg.test(this.formInline.mobile)) {
        params.email = this.formInline.mobile;
      } else {
        params.mobile = this.formInline.mobile;
      }
      params.page=this.cur_page
      params.limit=this.pageSize
      this.loading = true;
      getUserData(params).then((res) => {
        this.tableData = res.data.data;
        this.loading = false;
      });
    },
    deptFormatter(row) {
      let value = null;
      this.deptOptionsUnTree.forEach(function (k, v) {
        if (row.dept == k.id) {
          value = k.name;
        }
      });
      return value;
    },
    roleFormatter(row) {
      let value = [];
      this.roleOptions.forEach(function (k, v) {
        row.role.forEach(function (l, j) {
          if (row.role.length > 1) {
            if (l == k.id) {
              value.push(k.name + "&");
            }
          } else {
            if (l == k.id) {
              value.push(k.name);
            }
          }
        });
      });
      if (value.length > 1) {
        const aaa = value.pop(-1);
        const bbb = aaa.split("&")[0];
        value.push(bbb);
        return value;
      } else {
        return value;
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loading = true;
      this.filterData();
    },
    handleCurrentChange(val) {
      this.cur_page = val;
      this.loading = true;
      this.filterData();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.reloadTable();
    },
    onSetting(row) {
      resetUserPassword(row.id).then(res =>{
        if (res.code === 2000) {
              successMsg(res.msg);
              this.reloadTable();
          }
      })
    },
  },
};
</script>
<style lang="scss" scoped>
.div_padding {
  padding: 10px 10px;
}
</style>
